//
//  MediatorViewController.m
//  Cunli
//
//  Created by 湛亚 on 15/6/23.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "MediatorViewController.h"
#import "MyDataService.h"
#import "NSString+MD5.h"
#import "Mediator.h"
#import "UIImageView+WebCache.h"
#import "ChatViewController.h"
#import "TongXunLu.h"
#import "PointsManager.h"
#import <AVFoundation/AVFoundation.h>
#import "UIColor+Addition.h"

@interface MediatorViewController (){
    
    UIImageView *headPicImg,*callmg,*chatImg,*videoImg;
    UILabel *nameLabel,*callCountLabel;
    UIButton *callButton,*chatButton,*videoButton;
    float screenWidth,screenHeight,headImgWidth,buttonWidth,gapWidth,lefeWidth;
    NSString *phoneString;
    Mediator *currentMediator;
    NSMutableArray *mediatorArray;
    NSInteger lastClick;//上一次点击的按钮
}

@end

@implementation MediatorViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.isInvisible = YES;
    self.title=@"调解员";
    self.view.backgroundColor=[UIColor whiteColor];
    NSDictionary *user=[[NSUserDefaults standardUserDefaults]objectForKey:@"userinfo"];
    phoneString=[user objectForKey:@"username"];
    
    screenWidth=[UIScreen mainScreen].bounds.size.width;
    screenHeight=[UIScreen mainScreen].bounds.size.height;
    headImgWidth=70*(screenWidth/320.0);
    buttonWidth=50*(screenWidth/320.0);
    lefeWidth=60*(screenWidth/320.0);
    gapWidth=(screenWidth-buttonWidth*3-lefeWidth*2)/2.0;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleCallNotification:) name:@"callOutWithChatter" object:nil];
    
//    [self createNavBtn];
    [self getMediatorInfo];
    
    if (![[NSUserDefaults standardUserDefaults]objectForKey:@"huanXinInfo"]) {
        NSLog(@"本地无环信用户");
        [PointsManager getAllHuanXinUserInfo];
    }
}

/*
-(void)createNavBtn{
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 28, 28);
    [leftBtn setImage:[UIImage imageNamed:@"regback01"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    leftBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftBarItem;
}

-(void)goBack{
    
    [self.navigationController popViewControllerAnimated:YES];
}
*/
-(void)createView{
    
    float height;
    if (screenWidth==320) {
        height=100;
    }else{
        height=150;
    }
    
    //头像
    headPicImg=[[UIImageView alloc]initWithFrame:CGRectMake((screenWidth-headImgWidth)/2.0,height, headImgWidth, headImgWidth)];
    headPicImg.layer.cornerRadius = headImgWidth/2.0;
    headPicImg.clipsToBounds = YES;
    [headPicImg setImageWithURL:[NSURL URLWithString:currentMediator.pic] placeholderImage:[UIImage imageNamed:@"default_touxiang.png"]];
    [self.view addSubview:headPicImg];
    height=headImgWidth+height+20;
    
    //姓名
    nameLabel=[self createLabelWithFrame:CGRectMake((screenWidth-headImgWidth)/2.0,height, headImgWidth, 20) andTitle:currentMediator.turename andFont:17.0 andColor:0x000000];
    [self.view addSubview:nameLabel];
    height=height+40;
    
    //通话次数
    callCountLabel=[self createLabelWithFrame:CGRectMake((screenWidth-150)/2.0,height, 150, 20) andTitle:[NSString stringWithFormat:@"已通话%d起",currentMediator.callcount] andFont:15.0 andColor:0x000000];
    [self.view addSubview:callCountLabel];
    height=height+40;
    
    //电话，对话，视频按钮
    
    callmg=[[UIImageView alloc]initWithFrame:CGRectMake(lefeWidth,height, buttonWidth, buttonWidth)];
    callmg.userInteractionEnabled=YES;
    callmg.image=[UIImage imageNamed:@"callimg"];
    UITapGestureRecognizer *callTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(callMediator)];
    [callmg addGestureRecognizer:callTap];
    [self.view addSubview:callmg];
    
    chatImg=[[UIImageView alloc]initWithFrame:CGRectMake(lefeWidth+gapWidth+buttonWidth, height, buttonWidth, buttonWidth)];
    chatImg.userInteractionEnabled=YES;
    chatImg.image=[UIImage imageNamed:@"chatimg"];
    UITapGestureRecognizer *chatTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(chatWithMediator)];
    [chatImg addGestureRecognizer:chatTap];
    [self.view addSubview:chatImg];
    
    videoImg=[[UIImageView alloc]initWithFrame:CGRectMake(lefeWidth+gapWidth*2+buttonWidth*2, height, buttonWidth, buttonWidth)];
    videoImg.userInteractionEnabled=YES;
    videoImg.image=[UIImage imageNamed:@"videoimg"];
    UITapGestureRecognizer *videoTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(videoWithMediator)];
    [videoImg addGestureRecognizer:videoTap];
    [self.view addSubview:videoImg];
    
    height=height+buttonWidth+5;
    
    UILabel *callLabel=[self createLabelWithFrame:CGRectMake(lefeWidth, height, buttonWidth, 20) andTitle:@"电话" andFont:15 andColor:0x000000];
    [self.view addSubview:callLabel];
    
    UILabel *chatLabel=[self createLabelWithFrame:CGRectMake(lefeWidth+gapWidth+buttonWidth, height, buttonWidth, 20) andTitle:@"对话" andFont:15.0 andColor:0x000000];
    [self.view addSubview:chatLabel];
    
    UILabel *videoLabel=[self createLabelWithFrame:CGRectMake(lefeWidth+gapWidth*2+buttonWidth*2, height, buttonWidth, 20) andTitle:@"视频"  andFont:15.0 andColor:0x000000];
    [self.view addSubview:videoLabel];
}

- (void)handleCallNotification:(NSNotification *)notification
{
    id object = notification.object;
    if ([object isKindOfClass:[NSDictionary class]]) {
        //开始call
        self.isInvisible = YES;
    }
    else
    {
        //结束call
        self.isInvisible = NO;
    }
}

#pragma mark - 获取联络员信息

-(void)getMediatorInfo{
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:[Config getOwnAreaids] forKey:@"areaids"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"mediator.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        
        if ([[result objectForKey:@"response"] isEqualToString:@"mediator"]) {
            
            NSArray *listArray=[result objectForKey:@"list"];
            
            if (listArray.count<1) {
                
                UILabel *remindLab=[[UILabel alloc]initWithFrame:CGRectMake((screenWidth-150)/2.0, 150, 150, 30)];
                remindLab.textColor=[UIColor convertHexColorToUIColor:0x999999];
                remindLab.textAlignment=1;
                remindLab.text=@"本村未设置调解员";
                [self.view addSubview:remindLab];
                return ;
            }
            
            mediatorArray=[[NSMutableArray alloc]init];
            
            for (NSDictionary *dic in listArray) {
                //Mediator *mediator=[[Mediator alloc]initWithDictionary:dic];
                Mediator *mediator=[Mediator yy_modelWithDictionary:dic];
                [mediatorArray addObject:mediator];
            }
            //当前为数组里第一个调解员
            currentMediator=[mediatorArray firstObject];
            [self createView];
            
            //联络员个数大于一个
            if (mediatorArray.count>1) {
                [self createChooseMediatorView];
                lastClick=100;
            }
            
        }else{
            
            [Config showHUDWithText:@"获取信息失败!" andImage:@"error"];
            return ;
        }
        
    }failureAction:^{
        [Config showHUDWithText:@"获取信息失败!" andImage:@"error"];
    }];
}

#pragma mark - 拨打电话

- (void)callMediator {
    
    if ([self isShield]) {
        [self showAlertWithMessage:@"您已被村联络员屏蔽在该村的发言。如需申诉,请到“我-消息-通讯录”中与联络员进行联系"];
        return;
    }
    if ([phoneString isEqualToString:currentMediator.mobile]) {
        [self showAlertWithMessage:@"不能与自己通话"];
        return;
    }
    NSLog(@"拨打电话");
    
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",currentMediator.mobile];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.view addSubview:callWebview];
    //发送通话记录
    [self addCallRecord];
}

#pragma mark - 进入聊天界面

- (void)chatWithMediator {
    
    if ([self isShield]) {
        [self showAlertWithMessage:@"您已被村联络员屏蔽在该村的发言。如需申诉,请到“我-消息-通讯录”中与联络员进行联系"];
        return;
    }
    if ([phoneString isEqualToString:currentMediator.mobile]) {
        [self showAlertWithMessage:@"不能与自己对话"];
        return;
    }
    ChatViewController *chatVC=[[ChatViewController alloc]initWithChatter:currentMediator.huanxin_username isGroup:NO];
    chatVC.title=currentMediator.turename;
    chatVC.chatPicUrl=currentMediator.pic;
    chatVC.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:chatVC animated:YES];
    //发送对话积分请求
    [PointsManager sendPointWithUserid:[NSString stringWithFormat:@"%d",currentMediator.userid] andType:@"2"];
}

#pragma mark - 视频通话

- (void)videoWithMediator {
    
    if ([self isShield]) {
        [self showAlertWithMessage:@"您已被村联络员屏蔽在该村的发言。如需申诉,请到“我-消息-通讯录”中与联络员进行联系"];
        return;
    }
    if ([phoneString isEqualToString:currentMediator.mobile]) {
        [self showAlertWithMessage:@"不能与自己视频"];
        return;
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"callOutWithChatter" object:@{@"chatter":currentMediator.huanxin_username, @"type":[NSNumber numberWithInt:eCallSessionTypeVideo]}];
    //发送视频积分请求
    [PointsManager sendPointWithUserid:[NSString stringWithFormat:@"%d",currentMediator.userid] andType:@"1"];
}

#pragma mark - 发送通话记录

-(void)addCallRecord{
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:[NSString stringWithFormat:@"%d",currentMediator.userid] forKey:@"touserid"];
    [CheckParams setObject:@"1分钟" forKey:@"call_time"];
    [CheckParams setObject:@"1" forKey:@"type"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"add_caselog.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        
        
    }failureAction:^{
        
    }];
}

#pragma mark -切换联络员

-(void)createChooseMediatorView{
    
    if (mediatorArray.count==2) {
        lefeWidth=90*(screenWidth/320.0);
        gapWidth=screenWidth-buttonWidth*2-lefeWidth*2;
    }
    for (int i=0; i<mediatorArray.count; i++) {
        
        Mediator *mediator=[mediatorArray objectAtIndex:i];
        UIImageView *headImg=[[UIImageView alloc]initWithFrame:CGRectMake( lefeWidth+i*(buttonWidth+gapWidth), 40 , buttonWidth , buttonWidth )];
        headImg.userInteractionEnabled=YES;
        headImg.layer.cornerRadius = buttonWidth/2.0;
        headImg.clipsToBounds = YES;
        headImg.tag=i+100;
        [headImg setImageWithURL:[NSURL URLWithString:mediator.pic] placeholderImage:[UIImage imageNamed:@"default_touxiang.png"]];
        UITapGestureRecognizer *headTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeCurrentMediatorInfo:)];
        [headImg addGestureRecognizer:headTap];
        [self.view addSubview:headImg];
        
        if (i!=0) {
            headImg.alpha=0.4;
        }
    }
}

-(void)changeCurrentMediatorInfo:(UIGestureRecognizer *)currentTap{
    
    NSLog(@"%@",currentTap);
    if (lastClick==currentTap.view.tag) {
        return;
    }
    currentTap.view.alpha=1;
    //找到上个头像设置透明度
    UIImageView *lastImgView=(UIImageView *)[self.view viewWithTag:lastClick];
    lastImgView.alpha=0.4;
    lastClick=currentTap.view.tag;
    currentMediator=[mediatorArray objectAtIndex:currentTap.view.tag-100];
    [headPicImg setImageWithURL:[NSURL URLWithString:currentMediator.pic] placeholderImage:[UIImage imageNamed:@"default_touxiang.png"]];
    nameLabel.text=currentMediator.turename;
    callCountLabel.text=[NSString stringWithFormat:@"已电话%d次",currentMediator.callcount];
}

- (void)showAlertWithMessage:(NSString *)message
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

-(UILabel *)createLabelWithFrame:(CGRect)frame andTitle:(NSString *)title andFont:(CGFloat)fontSize andColor:(NSInteger)hexColor{
    
    UILabel *label=[[UILabel alloc]initWithFrame:frame];
    label.textColor=[UIColor convertHexColorToUIColor:hexColor];
    label.textAlignment=1;
    label.font=[UIFont systemFontOfSize:fontSize];
    label.text=title;
    return label;
}

#pragma mark - 判断是否被屏蔽发言

-(BOOL)isShield{
    
    NSDictionary *user=[[NSUserDefaults standardUserDefaults]objectForKey:@"userinfo"];
    NSString *userRoleString=[user objectForKey:@"is_banned"];
    if ([userRoleString isEqualToString:@"1"]) {
        return YES;
    }else{
        return NO;
    }
}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"callOutWithChatter" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
